package com.example.controller;

import com.example.common.RequirePermission;
import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.PurchaseDTO;
import com.example.service.PurchaseService;
import com.example.vo.PurchaseRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购买控制器
 */
@RestController
@RequestMapping("/api/purchase")
@CrossOrigin
public class PurchaseController {
    
    @Autowired
    private PurchaseService purchaseService;
    
    /**
     * 用户购买商品
     */
    @PostMapping("/buy")
    @RequirePermission("user:purchase:buy")
    public Result<Void> purchaseProduct(@RequestBody PurchaseDTO purchaseDTO) {
        return purchaseService.purchaseProduct(purchaseDTO);
    }
    
    /**
     * 获取当前用户的购买记录
     */
    @GetMapping("/my-records")
    @RequirePermission("user:purchase:view")
    public Result<List<PurchaseRecordVO>> getMyPurchaseRecords() {
        return purchaseService.getMyPurchaseRecords();
    }
    
    /**
     * 分页查询当前用户的购买记录
     */
    @GetMapping("/my-records/page")
    @RequirePermission("user:purchase:view")
    public Result<PageResult<PurchaseRecordVO>> getMyPurchasePage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {
        return purchaseService.getMyPurchasePage(page, size, keyword);
    }
    
    /**
     * 分页查询所有用户的购买记录（管理员使用）
     */
    @GetMapping("/all-records/page")
    @RequirePermission("admin:purchase:view")
    public Result<PageResult<PurchaseRecordVO>> getAllPurchasePage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {
        return purchaseService.getAllPurchasePage(page, size, keyword);
    }
    
    /**
     * 根据ID查询购买记录详情
     */
    @GetMapping("/{id}")
    @RequirePermission("user:purchase:view")
    public Result<PurchaseRecordVO> getPurchaseRecordById(@PathVariable Long id) {
        return purchaseService.getPurchaseRecordById(id);
    }
    
    /**
     * 根据商品ID查询购买记录（管理员使用）
     */
    @GetMapping("/by-product/{productId}")
    @RequirePermission("admin:purchase:view")
    public Result<List<PurchaseRecordVO>> getPurchaseRecordsByProductId(@PathVariable Long productId) {
        return purchaseService.getPurchaseRecordsByProductId(productId);
    }
    
    /**
     * 取消购买记录
     */
    @PutMapping("/cancel/{id}")
    @RequirePermission("user:purchase:cancel")
    public Result<Void> cancelPurchaseRecord(@PathVariable Long id) {
        return purchaseService.cancelPurchaseRecord(id);
    }
} 